/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hbb20.utils;

import ohos.app.Context;
import ohos.data.DatabaseHelper;

import java.lang.ref.WeakReference;

/**
 * Preferences.
 *
 * @author author
 * @version version
 */
public class Preferences {
    private static final String PREFERENCES_NAME = "preferences";
    private static WeakReference<Preferences> mPreferences;
    private final Context mContext;

    private Preferences(Context context) {
        mContext = context;
    }

    /**
     * get.
     *
     * @param context
     * @return Preferences
     */
    public static Preferences get(Context context) {
        if (mPreferences == null || mPreferences.get() == null) {
            mPreferences = new WeakReference<>(new Preferences(context.getApplicationContext()));
        }
        return mPreferences.get();
    }

    private ohos.data.preferences.Preferences getSharedPreferences() {
        DatabaseHelper databaseHelper = new DatabaseHelper(mPreferences.get().mContext);// context入参类型为ohos.app.Context
        return databaseHelper.getPreferences(PREFERENCES_NAME);
    }

    /**
     * clearPreferences.
     */
    public void clearPreferences() {
        getSharedPreferences().clear().flush();
    }

    /**
     * getString.
     *
     * @param var1 var1
     * @param var2 var2
     * @return String
     */
    public String getString(String var1, String var2) {
        return getSharedPreferences().getString(var1, var2);
    }

    /**
     * putString.
     *
     * @param var1 var1
     * @param var2 var1
     */
    public void putString(String var1, String var2) {
        getSharedPreferences().putString(var1, var2).flush();
    }

}
